package LeetCode.month02.day32;

import java.util.Arrays;

public class No1504 {
    public static void main(String[] args) {
        System.out.println(numSubmat(new int[][]{{0,1,1,0},{0,1,1,1},{1,1,1,0}}));
    }
    public static int numSubmat(int[][] mat) {
        int m = mat.length;
        int n = mat[0].length;
        int[][] st = new int[n+1][3];
        int[] height = new int[n];
        int ans = 0;
        for (int[] row : mat) {
            for (int i = 0; i < n; i++) {
                if (row[i] == 0) {
                    height[i] = 0;
                } else {
                    height[i]++;
                }
            }
            st[0][0]=st[0][2]=-1;
            int top = 0;
            for (int i = 0; i < n; i++) {
                int h = height[i];
                while(st[top][2]>=h){
                    top--;
                }
                int left = st[top][0];
                int f = st[top][1];
                f+=(i-left)*h;
                ans +=f;
                top++;
                st[top][0]=i;
                st[top][1]=f;
                st[top][2]=h;
            }
        }
        return ans;
    }
    public static int numSubmat1(int[][] mat) {
        int m = mat.length;
        int n = mat[0].length;
        int num = 0;
        for (int top = 0; top < m; top++) {
            int[] arr = new int[n];
            for (int bottom = top; bottom < m; bottom++) {
                int h = bottom-top+1;
                int last = -1;
                for (int index = 0; index < n; index++) {
                    arr[index] += mat[bottom][index];
                    if(arr[index]==h) num+=index-last;
                    else last = index;
                }
            }
        }
        return num;
//        int[][] presum = new int[m+1][n+1];
//        for (int i = 1; i <= m; i++) {
//            for (int j = 1; j <= n; j++) {
//
//            }
//        }
    }

    public int getNum(int[] arr,int k){
        int n = arr.length;
        int num = 0;
        int index = -1;
        for (int i = 0; i < n; i++) {
            int x = arr[i];
            if(x!=k) index = i;
            else num+=i-index;
        }
        return num;
    }
}
